package com.zhangxin.aiInterview.manager.work_flow.resume_content_extraction;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zhangxin.aiInterview.model.dto.resume.ResumeData;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 简历内容提取智能体
 */
public class ResumeContentExtraction {

    // 替换为你的API Key 和 API Secret
    private static final String API_KEY = "cd5245ddf5444cfcedd25b57a29b4c0b";
    private static final String API_SECRET = "MzdhNDEzNzVkMDcyZDhhZTM3MWNjODhj";
    private static final String FLOW_ID = "7320062870086295554";  // 工作流 ID

    private static final String[] RESUME_CONTENT = {"【教育经历】", "【专业技能】","【实习经历】", "【项目经历】", "【校园经历】","【工作经历】", "【获奖证书】","【自我评价】"};

    public static void main(String[] args) {
        ResumeData resumeData = resumeExtraction("https://zx-1343343346.cos.ap-chongqing.myqcloud.com/ai_interview/resume_pdf/1916016714226561026/jpPZGr8B-java后端实习简历.pdf");
        System.out.println(resumeData);
    }
    /**
     * 简历内容提取
     * @param resumeUrl 简历路径
     */
    public static ResumeData resumeExtraction(String resumeUrl) {

        StringBuilder result = new StringBuilder();
        try {
            // 1. 构建请求体 JSON（使用 Hutool）
            JSONObject parameters = new JSONObject();
            parameters.put("AGENT_USER_INPUT", "提取内容");
            parameters.put("RESUME_PDF", resumeUrl);

            JSONObject requestBody = new JSONObject();
            requestBody.put("flow_id", FLOW_ID);
            requestBody.put("uid", "123");
            requestBody.put("stream", true);
            requestBody.put("parameters", parameters);

            // 2. 构建请求 URL
            URL url = new URL("https://xingchen-api.xf-yun.com/workflow/v1/chat/completions");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 3. 设置请求方法和头部
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");

            // 设置 Authorization
            String authorizationHeader = "Bearer " + API_KEY + ":" + API_SECRET;
            connection.setRequestProperty("Authorization", authorizationHeader);
            connection.setDoOutput(true);
            // 4. 发送请求数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.toString().getBytes(StandardCharsets.UTF_8);
                os.write(input);
            }
            // 5. 读取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        if(StrUtil.isBlank(line)) continue;
                        String content = getContent(line);
                        result.append(content);
                    }
                }
            } else {
                System.out.println("Error: HTTP " + responseCode);
                try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {
                    StringBuilder errorResponse = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        errorResponse.append(line);
                    }
                    System.out.println("Error Response: " + errorResponse);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return processResume(result.toString());
    }

    /**
     * 处理简历
     * @param resumeContent
     * @return 简历各部分内容封装
     */
    public static ResumeData processResume(String resumeContent) {
        System.out.println("简历提取内容原始数据：   "+resumeContent);
        //获取每部分的内容
        Map<String, String> sections = getResumeSection(resumeContent);
        String education = sections.get("【教育经历】");
        String skills = sections.get("【专业技能】");
        String internship = sections.get("【实习经历】");
        String projectExperience = sections.get("【项目经历】");
        String workExperience = sections.get("【工作经历】");
        String schoolExperience = sections.get("【校园经历】");
        String certificate = sections.get("【获奖证书】");
        String selfEvaluation = sections.get("【自我评价】");
        //封装实例
        return ResumeData.builder()
                .education(education)
                .skill(skills)
                .internship(internship)
                .projectExperience(projectExperience)
                .workExperience(workExperience)
                .schoolExperience(schoolExperience)
                .certificate(certificate)
                .evaluation(selfEvaluation)
                .build();
    }

    /**
     * 获取简历每部分的内容
     * @param pdfText
     * @return
     */
    private static Map<String, String> getResumeSection(String pdfText){
        String[] lines = pdfText.split("\\r?\\n"); // 兼容不同换行符
        Map<String, String> sections = new LinkedHashMap<>();
        String currentSection = null;
        StringBuilder contentBuilder = new StringBuilder();
        //遍历每一个数据行
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i].trim();
            // 检查当前数据行是否包含章节标题
            Optional<String> matchedTitle = Arrays.stream(RESUME_CONTENT)
                    .filter(title -> line.startsWith(title) || line.matches(title + "[：:].*"))
                    .findFirst();
            //检查当前是否存在章节
            if (matchedTitle.isPresent()) {
                // 保存上一个章节
                if (currentSection != null) {
                    sections.put(currentSection, contentBuilder.toString().trim());
                }
                // 开始新章节
                currentSection = matchedTitle.get();
                contentBuilder = new StringBuilder();
            }
            // 收集当前章节内容
            else if (currentSection != null) {
                contentBuilder.append(line).append("\n");
            }
        }
        // 添加最后一个章节
        if (currentSection != null) {
            sections.put(currentSection, contentBuilder.toString().trim());
        }
        return sections;
    }

    /**
     * 处理智能体回复内容格式
     * @param jsonStr
     * @return
     */
    public static String getContent(String jsonStr) {
        // 去掉前缀 "data: " 并修正格式
        jsonStr = jsonStr.replaceFirst("^data:\\s*", "").trim();

        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);

        return jsonObject
                .getJSONArray("choices")
                .getJSONObject(0)
                .getJSONObject("delta")
                .getStr("content");
    }
}